package com.mls.fivedistrict.log;

import com.mls.fivedistrict.enums.UserOperate;
import com.mls.fivedistrict.pojo.User;
import com.mls.fivedistrict.pojo.UserLog;
import com.mls.fivedistrict.server.LogService;
import com.mls.fivedistrict.util.JsonUtils;
import com.mls.fivedistrict.util.jedis.RedisPoolUtil;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by chenxiuxiang on 2018/4/6.
 */
@Aspect
@Component
public class LogAspect {
    @Resource(name = "logService")
    LogService logService;

    @Pointcut("@annotation(com.mls.fivedistrict.enums.UserOperate)")
    public void controllerAspecta() {

    }

    @AfterReturning(value = "controllerAspecta() && @annotation(annotation) &&args(object,..) ", argNames = "annotation,object")
    public void interceptorApplogicA(UserOperate annotation, Object object) {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String token = request.getHeader("token");
        if (!StringUtils.isEmpty(token)) {

            if (StringUtils.isEmpty(RedisPoolUtil.get(token))) {
                User user = JsonUtils.jsonToPojo(RedisPoolUtil.get(token), User.class);
                String moduleName = annotation.moduleName();
                String option = annotation.option();
                UserLog userLog = new UserLog();
                userLog.setUserId(user.getId());
                userLog.setIp(getIpAddr(request));
                userLog.setModulName(moduleName);
                userLog.setAction(option);
                userLog.setPhone(user.getPhone());
                logService.addUserLog(userLog);
            }

        }
    }

    /**
     * 获取IP地址
     *
     * @param request
     * @return
     */
    private String getIpAddr(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
